﻿using System;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Shared;

namespace RabbitMQConsumer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var factory = new ConnectionFactory { HostName = "localhost" };

            var conn = factory.CreateConnection();

            using (var channel = conn.CreateModel())
            {
                //3、通过通道声明队列   队列、消息
                //4、持久化----队列
                //channel.QueueDeclare(queue: "lhy", durable: true, exclusive: false, autoDelete: false, arguments: null);


                //声明交换器
                channel.ExchangeDeclare(Exchange.Name, ExchangeType.Topic);

                var queueName = channel.QueueDeclare().QueueName;

                //绑定到指定的交换器
                channel.QueueBind(queue: queueName, exchange: Exchange.Name, routingKey: args[0]);

                //公平调度 - 能者多劳
                //channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);


                //创建消息费
                var consumer = new EventingBasicConsumer(channel);                
                
                //接收消息
                consumer.Received += (object sender, BasicDeliverEventArgs e) => {

                    var bytes = e.Body.ToArray();

                    var msg = Encoding.UTF8.GetString(bytes);

                    //Thread.Sleep(TimeSpan.FromSeconds(Convert.ToInt16(args[0])));

                    Console.WriteLine($"接收到的消息:{msg}");

                    //channel.BasicAck(deliveryTag: e.DeliveryTag, multiple: false);
                };

                //消费消息
                channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer);

                Console.ReadLine();
            }
        }        
    }
}
